package com.yups.dao;

import com.yups.model.Carousels;
import com.yups.model.Service;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * 轮播图数据控制类
 *
 * @author 于鹏生
 */
public class CarouselsDao extends BaseDao {
	public boolean add(Carousels carousels) {
		try {
			String sql = "INSERT INTO `db_book`.`carousels` (`id`, `icon`, `service_id`)\n"
					+ " VALUES (?, ?, ?)";
			return queryRunner.execute(sql,
					carousels.getId(),
					carousels.getIcon(),
					carousels.getService().getId()
			) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean delete(Carousels carousels) {
		try {
			String sql = "DELETE\n"
					+ " FROM\n"
					+ "  `db_book`.`carousels`\n"
					+ " WHERE `id` = ?";
			return queryRunner.execute(sql, carousels.getId()) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean update(Carousels carousels) {
		try {
			String sql = "UPDATE\n"
					+ "  `db_book`.`carousels`\n"
					+ " SET\n"
					+ "  `icon` = ?,\n"
					+ "  `service_id` = ?\n"
					+ " WHERE `id` = ?";
			return queryRunner.execute(sql,
					carousels.getIcon(),
					carousels.getService().getId(),
					carousels.getId()
			) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public Carousels get(Carousels carousels) {
		try {
			String sql = "SELECT\n"
					+ "  `id`,\n"
					+ "  `icon`,\n"
					+ "  `service_id`\n"
					+ " FROM\n"
					+ "  `db_book`.`carousels`\n"
					+ " WHERE id = ?";
			return queryRunner.query(sql, rs -> {
						if (rs.next()) {
							return new Carousels(
									rs.getInt("id"),
									rs.getString("icon"),
									new Service(rs.getInt("service_id"))
							);
						}
						return null;
					},
					carousels.getId()
			);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Carousels> getAll() {
		String sql = "select id, icon, service_id"
				+ " from carousels"
				+ " order by id";
		try {
			return queryRunner.query(sql,
					rs -> {
						List<Carousels> carousels = new LinkedList<>();
						while (rs.next()) {
							carousels.add(
									new Carousels(
											rs.getInt("id"),
											rs.getString("icon"),
											new Service(rs.getInt("service_id"))
									)
							);
						}
						return carousels;
					});
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
